const { WechatOrder } = require('../../schemas/wechatSchema')
const { timeFormat } = require('../../utils')

// 分页查询 维修服务
const serviceOrder = async (request, reply) => {
  const { currentPage = 1, pageSize = 10 } = request.query
  let page = Math.max(parseInt(currentPage, 10), 1)
  let size = Math.max(parseInt(pageSize, 10), 1)

  const skip = (page - 1) * size

  const [userData, total] = await Promise.all([
    WechatOrder.find({}, { _id: 0, __v: 0 })
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(size)
      .exec(),
    WechatOrder.countDocuments().exec(),
  ])

  const _userData = userData.map((item) => ({
    ...item._doc,
    createdAt: timeFormat(item.createdAt),
    updatedAt: timeFormat(item.updatedAt),
  }))

  return reply.code(200).send({
    code: reply.statusCode,
    message: '',
    data: _userData,
    totalPages: Math.ceil(total / size),
    currentPage: page,
    pageSize: size,
    total,
    error: null,
  })
}

/**
 * 后台更新 服务 状态
 * @param {*} request
 * @param {*} reply
 * @returns
 */
const updateStatus = async (request, reply) => {
  const { orderId, status } = request.body
  if (!orderId || !status) {
    return reply.code(400).send({
      code: 400,
      message: 'Invalid orderId or status',
      error: 'Bad Request',
    })
  }

  const order = await WechatOrder.findByIdAndUpdate(
    orderId,
    { status },
    { new: true, fields: { _id: 0, __v: 0 } }
  )
  if (!order) {
    return reply.code(404).send({
      code: 404,
      message: 'Order not found',
      error: 'Not Found',
    })
  }

  return reply.code(200).send({
    code: reply.statusCode,
    message: 'Status updated successfully',
    data: order,
    error: null,
  })
}

module.exports = {
  serviceOrder,
  updateStatus,
}
